package com.sh4.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sh4.dao.impl.BaseDaoImpl;
import com.sh4.dao.impl.PermissionDaoImpl;
import com.sh4.dao.impl.PermissionResourceDaoImpl;
import com.sh4.entity.Permission;
import com.sh4.entity.PremissionResources;
import com.sh4.entity.SystemEnum;
import com.sh4.service.PermissionService;
import com.sh4.util.ContextHeader;

import net.sf.json.JSONObject;

@Service("permissionServiceImpl")
@Transactional
public class PermissionServiceImpl extends BaseDaoImpl<SystemEnum> implements PermissionService{
	
	@Autowired
	PermissionDaoImpl permissionDaoImpl;
	
	@Autowired
	PermissionResourceDaoImpl permissionResourceDao;
	
	@Value(value="${conf.companyCode}")
	private String companyCode;
	
	@Override
	public void savePermission(Permission p) {
		
		if(StringUtils.isNotBlank(p.getId())) {
			p.setUpdateBy(ContextHeader.getUserCode());
			p.setUpdateDate(new Date());
		}else {
			p.setCreateBy(ContextHeader.getUserCode());
			p.setCreateDate(new Date());
		}
		permissionDaoImpl.saveOrUpdate(p);
		
	}

	@Override
	public Map<String , Object> list(int pageNO , int pageSize , JSONObject params) {
		Map<String , Object> result = new HashMap<String ,Object>();
		int status = 200;
		String hql = "from Permission s";
		result.put("dataList", permissionDaoImpl.getPage(pageNO, pageSize, hql));
		int total = 0;
		total = permissionDaoImpl.permissionCount(companyCode);
		result.put("total", total);
		result.put("status", status);
		return result;
	}

	@Override
	public void deletePermission(Permission p) {
		
		permissionDaoImpl.delete(p);
	}

	@Override
	public void savePermissionResource(List<String> menuIds,String permissionId) {
		
		//先清除原来的权限配置
		permissionDaoImpl.deletePermission(permissionId);
		
		//在重新配置
		for(String menuId: menuIds) {
			PremissionResources pres = new PremissionResources();
			pres.setPermissionId(permissionId);
			pres.setResourceId(menuId);
			pres.setCreateBy(ContextHeader.getUserCode());
			pres.setCreateDate(new Date());
			
			permissionResourceDao.saveOrUpdate(pres);
		}
		
	}

	@Override
	public List<String> getPermissionResource(String permissionId) {
		
		return permissionResourceDao.getPermissionResources(permissionId);
		
	}
	
	

}
